#!/usr/bin/python
import ConfigParser
import os
import sys
from debug import *
import hashlib
import tempfile
import shutil
import tarfile
from package import *

class serviceObj:
    def __init__(self):
        self.source = "";
        self.destination = "";
        self.build  = False;
        self.depends= "";
        self.make   = "Makefile";
        self.install= "";

class make:
    def __init__(self):
        self.rootPath = "";
        self.version  = 0;
        self.services = {};
        self.svnOptions =[];
        self.initPath = os.getcwd();
        
        self.getConfig();

    def getConfig(self):
        config=ConfigParser.ConfigParser()
        config.read("make.conf")


        self.svnOptions = config.options("info")
        for option in self.svnOptions:
            self.option = config.get("info",option);
        self.filterOptions();

        sections = config.sections()
        services = []
        for serviceName in sections:
            if serviceName != "info" :
                services.append(serviceName);

        for serviceName in services:
            if config.get(serviceName , "source")=="":
                print "there are no "+serviceName+" svn path in make.conf. please set the path first!"
                exit(1)
            newService = serviceObj()
            self.services[serviceName] = newService;
            newService.source = config.get(serviceName, "source")
            newService.destination = config.get(serviceName,"destination")
            if config.has_option(serviceName,"depends"):
                newService.depends = config.get(serviceName,"depends")
            if config.has_option(serviceName,"install"):
                newService.install = config.get(serviceName,"install")
            if config.getint(serviceName,"build") == 1:
                newService.build  = True
            else:
                continue;
            newService.make = config.get(serviceName,"make")

    def filterOptions(self):
        if hasattr (self,"username") and hasattr (self, "password"):
            self.userOptionStr = " --username "+self.username+" --password "+self.password+" "
        else:
            self.userOptionStr = "";


    def getCode(self, serviceName):
        service = self.getServiceObj(serviceName)
        if service.depends:
            for depService in service.depends.split():
                self.getCode(depService)
        os.system("svn export "+self.userOptionStr+" --force "+service.source+" "+service.destination)

    def getAllCode(self):
        for service in self.services.keys():
             self.getCode(service);

    def removeAll(self):
        for service in self.services.keys():
            self.remove(service)

    def remove(self, serviceName):
        os.system("rm -rf "+self.services[serviceName].destination);

    def build(self, serviceName):
        service = self.getServiceObj(serviceName)
        if service.depends:
            for depService in service.depends.split():
                self.build(depService)
        if not service:
            print "CALL ERORR: there are no "+serviceName;
        if not service.build:
            print serviceName+" needn't build"
            return
        os.chdir(service.destination);
        if not os.path.exists(service.make):
            print "there are no "+serviceName+"  Makefile. build fail!"
            exit(1)
        BUILDINFO(serviceName)
        os.system("make -f "+service.make);
        os.chdir(self.initPath);

    def buildAll(self):
        for buildService in self.services.keys():
            self.build(buildService)

    def clean(self, service):
        service = self.getServiceObj(serviceName)
        if not service:
            print "CALL ERORR: there are no "+serviceName;
        os.chdir(service.destination);
        if not os.path.exists(service.make):
            print "there are no "+service+"  Makefile. build fail!"
            exit(1)
        CLEANINFO(service)
        os.system("make -f "+service.make+"clean");
        os.chdir(self.initPath);
        
    def getServiceObj(self, serviceName):
        if self.services.has_key(serviceName):
            return self.services[serviceName]
        else:
            return NULL;

class packageOld:
    def __init__(self ,services):
        self.services = services;
        self.initPath = os.getcwd();


    def getServiceObj(self, serviceName):
        if self.services.has_key(serviceName):
            return self.services[serviceName]
        else:
            return NULL;


    def checkFiles(self,serviceName):
        service = self.getServiceObj(serviceName)
        if not service:
             print "NO SERVICE:"+serviceName;
             exit(1)
        if not service.install:
             print "NO INSTALL SET:"+serviceName;
             exit(1)
        if not os.path.isdir(service.destination):
            print "check files error , no directory",service.destination;
            exit(1);
        os.chdir(service.destination)
        installStr = service.install
        installs = installStr.split();
        for install in installs:
            if os.path.isdir(install) or os.path.isfile(install):
                 continue;
            else:
                 print "no file or directory "+install+ " in "+serviceName
                 return False;
        os.chdir(self.initPath)
        print "FINISH CHECK "+serviceName+", ALL INSTALL FILE EXISTS."
        return True;

    def checkAllFiles(self):
        for ins in self.services.keys():
            if self.checkFiles(ins):
                continue;
            else :
                return False;
        return True;

    def MD5File(self, fileName):
        try:
            f = file(fileName,'rb')
        except:
            print 'Failed to open file '+file;
            exit;
        m = hashlib.md5();
        while True:
            d = f.read(8096)
            if not d:
                break;
            m.update(d)
        return m.hexdigest()

    def packageFile(self,serviceName):
        if not self.checkFiles(serviceName):
            exit(1)
        tempf = tempfile.mkdtemp();
        service = self.getServiceObj(serviceName)
        print "make temp directory ",tempf
        installs  = service.install.split()
        for install in installs:
            if os.path.islink(install):
               print "THERE ARE LINK IN INSTALL...PANIC!!!!"            
            filePath = os.path.join ( service.destination , install );
            os.system("mkdir -p  "+os.path.dirname( os.path.join(tempf,install)))
            os.system("cp -rfa "+filePath+"  "+os.path.join(tempf,install))
        
        
        os.chdir(service.destination)
        md5file = file(os.path.join( tempf, "MD5SUM" ), "wb");
        for install in installs:
            if os.path.isfile(install):
                md5file.writelines(install+ "	"+self.MD5File( install )+"\n")
            elif os.path.isdir(install):
                for parent, dirnames, filenames in os.walk(install):
                    if len(filenames):
                        for filename in filenames:
                            rePath = os.path.join( parent, filename );
                            md5file.writelines( rePath+ "	"+self.MD5File( rePath )+"\n")
        md5file.close()
        os.chdir(self.initPath)

        tar = tarfile.open(serviceName+".tar", "w")
        os.chdir(tempf)
        tar.add(".")
        os.chdir(self.initPath)
        tar.close()
    

def getArg():
    return sys.argv[1:];

service = getArg()[0]

a= make();
#for service in getArg():
#	a.getCode(service);
#	a.build(service);
#a.getAllCode();
#a.buildAll();
a.removeAll();
a.getCode(service)
a.build(service)

p = package(a.services)
p.packageFile(service)
#p.getPackageFiles(service)

